import { Hono } from 'hono'
import { z } from 'zod'
import { AuthService } from '@/services/authService'
import { asyncHandler, ValidationError } from '@/middleware/errorHandler'
import { authMiddleware, getCurrentUserId } from '@/middleware/auth'

const auth = new Hono()
const authService = new AuthService()

// 验证模式
const registerSchema = z.object({
  username: z.string().min(3).max(50),
  email: z.string().email(),
  password: z.string().min(8),
  displayName: z.string().max(100).optional()
})

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(1)
})

const refreshSchema = z.object({
  refreshToken: z.string()
})

const updateProfileSchema = z.object({
  displayName: z.string().max(100).optional(),
  bio: z.string().max(500).optional(),
  websiteUrl: z.string().url().optional(),
  githubUrl: z.string().url().optional(),
  avatarUrl: z.string().url().optional()
})

// 简单的验证中间件
const validateJson = (schema: z.ZodSchema) => {
  return async (c: any, next: any) => {
    try {
      const body = await c.req.json()
      const validatedData = schema.parse(body)
      c.set('validatedData', validatedData)
      await next()
    } catch (error) {
      if (error instanceof z.ZodError) {
        throw new ValidationError('Validation failed', error.errors)
      }
      throw error
    }
  }
}

// 开发者注册
auth.post('/register',
  validateJson(registerSchema),
  asyncHandler(async (c) => {
    const data = c.get('validatedData')

    const result = await authService.register(data)

    return c.json({
      success: true,
      data: result,
      message: 'Registration successful'
    }, 201)
  })
)

// 开发者登录
auth.post('/login',
  validateJson(loginSchema),
  asyncHandler(async (c) => {
    const data = c.get('validatedData')

    const result = await authService.login(data)

    return c.json({
      success: true,
      data: result,
      message: 'Login successful'
    })
  })
)

// 刷新Token
auth.post('/refresh',
  validateJson(refreshSchema),
  asyncHandler(async (c) => {
    const { refreshToken } = c.get('validatedData')

    const tokens = await authService.refreshToken(refreshToken)

    return c.json({
      success: true,
      data: { tokens },
      message: 'Token refreshed successfully'
    })
  })
)

// 获取当前用户信息 (需要认证)
auth.get('/me', authMiddleware(), asyncHandler(async (c) => {
  const userId = getCurrentUserId(c)

  if (!userId) {
    return c.json({
      success: false,
      error: {
        code: 'UNAUTHORIZED',
        message: 'Authentication required'
      }
    }, 401)
  }

  const profile = await authService.getProfile(userId)

  return c.json({
    success: true,
    data: { user: profile },
    message: 'User profile retrieved successfully'
  })
}))

// 获取个人信息
auth.get('/profile', asyncHandler(async (c) => {
  // 暂时使用模拟用户ID，等认证中间件实现后从token获取
  const userId = 'mock-user-id-123'

  const profile = await authService.getProfile(userId)

  return c.json({
    success: true,
    data: { user: profile },
    message: 'Profile retrieved successfully'
  })
}))

// 更新个人信息
auth.put('/profile',
  validateJson(updateProfileSchema),
  asyncHandler(async (c) => {
    const data = c.get('validatedData')
    // 暂时使用模拟用户ID
    const userId = 'mock-user-id-123'

    const profile = await authService.updateProfile(userId, data)

    return c.json({
      success: true,
      data: { user: profile },
      message: 'Profile updated successfully'
    })
  })
)

export default auth
